<?php
/**
 * Created by PhpStorm.
 * User: saving
 * Date: 2018/3/5
 * Time: 16:10
 */

namespace app\admin\controller\v1;

use app\admin\controller\Fun;
use app\common\Model\PayLog;
use think\Db;


/**
 * @title 后台-财务管理管理-V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class UserWithdraw extends Base
{
    /**
     * @title 用户提现列表
     * @description
     * @author saving
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserWithdraw desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:userWithdrawList desc:用户提现列表
     *
     * @param name:page type:string require:1 default: other: desc:页码
     * @param name:page_size type:string require:1 default: other: desc:每页个数
     * @param name:search type:string require:1 default: other: desc:查询数据
     * @param name:sort_field type:string require:1 default: other: desc:排序字段
     * @param name:sort_type type:string require:1 default: other: desc:0正序,1倒序
     *
     * @return data:['list'=>[],'total_num'=>2 ]
     */
    public function userWithdrawList()
    {

        $where = ['p.pay_event'=>3];
        //查询
        if (isset($this->param['search']) && $this->param['search'] != '') {
            $search = $this->param['search'];
            $where['p.order_num|u.nick_name|u.mobile'] = ['like', '%' . $search . '%'];
        }
        $used_sort_field = [
            'order_num', 'nick_name', 'mobile', 'status', 'create_time', 'amount', 'rest',
        ];
        if (isset($this->param['sort_field']) && $this->param['sort_field'] != '' && in_array($this->param['sort_field'], $used_sort_field) && isset($this->param['sort_type'])) {
            $order = [
                $this->param['sort_field'] => $this->sort_type[intval($this->param['sort_type'])]
            ];
        } else {
            $order = ['w.create_time' => $this->sort_type[1]];
        }
        $list = Db::table('sh_withdraw_log w')
            ->join('pay_log p', 'p.order_num=w.order_num')
            ->join('user u', 'u.uid=w.uid')
            ->join('user_balance ub', 'ub.uid=w.uid')
            ->join('admin_user au','au.uid = w.operator_uid','LEFT')
            ->where($where)
            ->order($order)
            ->field('
            w.id,
            w.zfb_account ,
            w.zfb_uname ,
            w.amount ,
            w.status ,
            w.create_time,
            p.order_num,
            u.nick_name,
            u.mobile,
            au.realname as operator_name,
            ub.recharge_balance,
            ub.withdraw_balance
            ')
            ->paginate($this->page_size, false, ['page' => $this->param['page']]);

        if ($list) {
            $WithdrawLog = new \app\common\Model\WithdrawLog();
            $data = [];
            foreach ($list->items() as $k => $v) {
                $arr = $v;
                $arr['amount'] = $v['amount']/config('convert_unit');
                //账户余额为 充值金额+可提现金额
                $arr['total_money'] = ($v['recharge_balance']/config('convert_unit')) + $v['withdraw_balance']/config('convert_unit');
                $arr['status'] = $WithdrawLog->_status[$v['status']];
                $arr['_status'] = strval($v['status']);
                $arr['total_money'] = sprintf("%.2f",$arr['total_money']);
                $data[] = $arr;
            }
            return Fun::success([
                'list' => $data,
                'total_num' => $list->total()
            ]);
        } else {
            return Fun::error('333333');
        }
    }

    /**
     * @title 修改提现状态
     * @description
     * @author saving
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserWithdraw desc:接口组(全局)
     * @header name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:command type:string require:1 default: other:alterUserWithdrawStatus desc:捎货人禁用恢复
     *
     * @param name:ids type:string require:1 default: other:10086,10087,10088 desc:列表id
     * @param name:status type:string require:1 default: other:0 desc:提现状态:0：申请已经提交，1：申请已经受理，2：转账已经完成，3：被驳回
     * @param name:reason type:string require:1 default: other:0 desc:驳回理由:状态为3时，传理由，其余状态传''
     *
     * @return data:[]
     */
    public function alterUserWithdrawStatus()
    {
        if(empty($this->param['ids'])){
            return Fun::error('999994');
        }
        $ids = explode(',', trim($this->param['ids'], ','));
        $updata = [];

        $updata['operator_uid'] = \app\common\Model\AdminUser::get(['acc_id' => $this->param['acc_id']])->uid;

        $WithdrawLog = New \app\common\Model\WithdrawLog();
        //用户状态:1为有效,0为禁用
        if (isset($this->param['status']) && in_array(intval($this->param['status']), [0,1,2,3])) {
            $updata['status'] = $this->param['status'];
        }else{
            return Fun::error('999994');
        }
        if (!empty($this->param['reason'])) {
            $updata['reason'] = $this->param['reason'];
        }
        if (count($updata) && count($ids)) {
            $WithdrawLog->where('id', 'in', $ids)
                ->update($updata);
            //改变用户冻结金额
            $find = $WithdrawLog->where('id', 'in', $ids)
                ->select();
            $update=[];
            foreach ($find as $key => $value) {
                $update['frozen_balance']=0;
                //如果状态为3说明为拒绝，要退款金额到余户余额
                if ($this->param['status']==3) {
                    $userbalance = DB::name('user_balance')->where(['uid'=>$value['uid']])->find();
                    $update['withdraw_balance'] = $userbalance['withdraw_balance']+$value['amount'];
                }elseif ($this->param['status'] == 2){
                    PayLog::where(['order_num' => $value->order_num])->update(['status' => 1]);
                }
                DB::name('user_balance')->where(['uid'=>$value['uid']])->update($update);
            }
            return Fun::success('000000');
        }
        return Fun::error('333332');
    }

    /**
     * @title 用户流水记录
     * @description
     * @author saving
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserWithdraw desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:UserPayList desc:用户流水记录
     *
     * @param name:page type:string require:1 default: other: desc:页码
     * @param name:search type:string require:1 default: other: desc:查询数据
     * @param name:sort_field type:string require:1 default: other: desc:排序字段
     * @param name:sort_type type:string require:1 default: other: desc:0正序,1倒序
     * @param name:pay_event type:string require:1 default: other: desc:用户操作:1充值,2下单,3提现,4收入
     * @param name:start_time type:string require:1 default: other: desc:用户操作开始查询时间
     * @param name:end_time type:string require:1 default: other: desc:用户操作结束查询时间
     *
     * @return data:[]
     */
    public function UserPayList()
    {
        //查询
        $where = ['s.status'=>1];
        if (isset($this->param['search']) && $this->param['search'] != '') {
            $search = $this->param['search'];
            $where['u.mobile|u.real_name|u.nick_name'] = ['like', '%' . $search . '%'];
        }
        if (isset($this->param['pay_event']) && $this->param['pay_event'] != '') {
            $where['s.pay_event'] = intval($this->param['pay_event']);
        }
        $where_time = '';
        //用户注册时间
        if (isset($this->param['start_time']) && $this->param['start_time'] != '') {
            $start_time = $this->param['start_time'];
            $where_time = "s.create_time >= '$start_time'";
        }
        if (isset($this->param['end_time']) && $this->param['end_time'] != '') {
            $end_time = $this->param['end_time'];
            if (strlen($where_time) > 5) {
                $where_time .= "AND s.create_time <= '$end_time'";
            } else {
                $where_time = "s.create_time <= '$end_time'";
            }
        }
        //可排序字段
        $used_sort_field = [
            'real_name',
            'mobile',
            'pay_event',
            'current_balance',
            'amount',
            'create_time',
        ];
        if (isset($this->param['sort_field']) && $this->param['sort_field'] != '' && in_array($this->param['sort_field'], $used_sort_field) && isset($this->param['sort_type'])) {
            $order = [
                $this->param['sort_field'] => $this->sort_type[intval($this->param['sort_type'])]
            ];
        } else {
            $order = ['s.create_time' => $this->sort_type[1]];
        }
        $list = Db::name('pay_log s')
            ->join([
                ['user u', 'u.uid=s.uid'],
            ])
            ->where($where)
            ->where($where_time)
            ->order($order)
            ->field('
            u.uid,
            u.real_name,
            u.mobile,
            s.pay_event,
            s.amount,
            s.current_balance,
            s.create_time
            ')
            ->paginate($this->page_size, false, ['page' => $this->param['page']]);
        if ($list) {
            $WithdrawLog = new \app\common\Model\WithdrawLog();
            $data = [];
            foreach ($list->items() as $key => $value) {
                $arr['pay_event'] = $WithdrawLog->pay_status[$value['pay_event']];
                $arr['_pay_event'] = $value['pay_event'];
                $value['amount'] = sprintf("%.2f",$value['amount'] / 100);
                $value['current_balance'] = sprintf("%.2f",$value['current_balance'] / 100);
                $data[] = $value;
            }
            return Fun::success(['list' => $data, 'total_num' => $list->total()]);
        } else {
            return Fun::error('333333');
        }
    }

    /**
     * @title 用户流水数据导出
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserWithdraw desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:exportUserPayList desc:用户流水数据导出
     *
     * @param name:search type:string require:1 default: other: desc:查询数据
     * @param name:sort_field type:string require:1 default: other: desc:排序字段
     * @param name:sort_type type:string require:1 default: other: desc:0正序,1倒序
     * @param name:pay_event type:string require:1 default: other: desc:用户操作:1: 充值 2：下单 3：提现 4：收入
     * @param name:start_time type:string require:1 default: other: desc:用户操作开始查询时间
     * @param name:end_time type:string require:1 default: other: desc:用户操作结束查询时间
     *
     * @return data:[]
     */
    public function exportUserPayList()
    {
        set_time_limit(0);
        ini_set('memory_limit', '2048M');
        //查询
        $where = ['s.status'=>1];
        if (isset($this->param['search']) && $this->param['search'] != '') {
            $search = $this->param['search'];
            $where['u.mobile|u.real_name|u.nick_name'] = ['like', '%' . $search . '%'];
        }
        if (isset($this->param['pay_event']) && $this->param['pay_event'] != '') {
            $where['s.pay_event'] = intval($this->param['pay_event']);
        }
        $where_time = '';
        //用户注册时间
        if (isset($this->param['start_time']) && $this->param['start_time'] != '') {
            $start_time = $this->param['start_time'];
            $where_time = "s.create_time >= '$start_time'";
        }
        if (isset($this->param['end_time']) && $this->param['end_time'] != '') {
            $end_time = $this->param['end_time'];
            if (strlen($where_time) > 5) {
                $where_time .= "AND s.create_time <= '$end_time'";
            } else {
                $where_time = "s.create_time <= '$end_time'";
            }
        }
        //可排序字段
        $used_sort_field = [
            'real_name',
            'mobile',
            'pay_event',
            'current_balance',
            'amount',
            'create_time',
        ];
        if (isset($this->param['sort_field']) && $this->param['sort_field'] != '' && in_array($this->param['sort_field'], $used_sort_field) && isset($this->param['sort_type'])) {
            $order = [
                $this->param['sort_field'] => $this->sort_type[intval($this->param['sort_type'])]
            ];
        } else {
            $order = ['s.create_time' => $this->sort_type[1]];
        }
        $list = Db::name('pay_log s')
            ->join([
                ['user u', 'u.uid=s.uid'],
            ])
            ->where($where)
            ->where($where_time)
            ->order($order)
            ->field('
            u.real_name,
            u.mobile,
            s.pay_event,
            s.amount,
            s.current_balance,
            s.create_time
            ')
            ->select();
        if ($list) {
            $file_name = './csv/' . date('YmdHis').'.csv';
            $header = ['姓名',  '手机号', '用户操作', '操作金额', '账户余额', '用户操作时间'];

            $WithdrawLog = new \app\common\Model\WithdrawLog();

            $data = [];
            foreach ($list as $key => $value) {
                $arr['pay_event'] = $WithdrawLog->pay_status[$value['pay_event']];
                $data[] = $value;
            }
            Fun::exportCsv($file_name,$header,$data);
            return Fun::success(['file_url'=>config('param.url').trim($file_name,'.')]);
        } else {
            return Fun::error('802002');//所选导出数据为空
        }
    }

}